package com.gking.resourcePool.filter;

import com.alibaba.fastjson.JSON;

import com.gking.resourcePool.utils.GetAuthInfoUtil;
import com.gking.resourcePool.common.BaseContext;
import com.gking.resourcePool.common.Result;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 检查用户是否已经完成登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*", asyncSupported = true)
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param requestURI 前端发起的请求
     * @return s
     */
    private boolean check(String requestURI) {
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/api/**",
                "/public/**",
                "/remote/api/**",
        };

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }


    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain
    ) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("LoginCheckFilter 拦截到请求：{}", requestURI);
        //2、判断本次请求是否需要处理
        boolean check = check(requestURI);

        //3、如果不需要处理，则直接放行
        if (check) {
            log.info("LoginCheckFilter 本次请求 {} 不需要登录、权限处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //如果需要处理请求，获取 Headers 中携带的 用户id 参数
        String token = request.getHeader("Authorization");

        GetAuthInfoUtil getAuthInfoUtil = new GetAuthInfoUtil(stringRedisTemplate, request);
        String userKey = getAuthInfoUtil.getTokenUserKey();
        log.info("检验 token 中的用户userKey id 为 ： {} ", userKey);

        // 最基本的校验，访问token是否合法
        if (userKey == null) {
            response.getWriter().write(JSON.toJSONString(Result.error("NoLogin")));
            return;
        }
        // 验证登录用户的一些信息是否存在
//        FIXME 兼容主应用访问子应用
//        if (!getAuthInfoUtil.verifyLoginUser()) {
//            response.getWriter().write(JSON.toJSONString(Result.error("NoLogin")));
//            return;
//        }


        String userId = getAuthInfoUtil.getUserServerInfo();
        log.info("检验 token 中的用户 id 为 ： {}", userId);


        //判断登录状态，如果已登录，则直接放行
        if (userId != null) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", request.getHeader("Authorization"));
            headers.put(HttpHeaders.COOKIE, request.getHeader(HttpHeaders.COOKIE));
            headers.put("c-device-id", request.getHeader("c-device-id"));
            BaseContext.setHeader(headers);

            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(Result.error("NoLogin")));
    }

}
